import router from '@/router'
import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 10000,
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 统一携带Token
    // 从pinia仓库中获取Token
    const useStore = useUserStore()
    const token = useStore.token
    // 判断Token是否存在
    if(token){
      // 统一携带Token
      config.headers.authosization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)
// 响应拦截器  数据剥离 + 异常处理(401 / 500)
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if(error.response.status === 401){
      // 1. 清除Token
      const useStore= useUserStore()
      useStore.removeToken()
      // 2. 跳转到登录页面
      // const  router = useRouter()
      // router.push('/login')
      router.push("/login")
      // 3. 提示用户
      return ElMessage.error('登录过期，请重新登录')
    }
    ElMessage.error(error.response.data.message || '请求错误')
    return Promise.reject(error)
  },
)
// 定义返回的数据类型
type Data<T>={
  code:number,
  msg:string,
  data:T
}
//封装请求方法
// submit =====> params / data 
const requestToAxios =<T>(url:string,method:Method,submitData?:object) => {
  return service.request<T,Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']:  submitData,
  })
}


export  { requestToAxios }
export default service
